const {
  getAppUser,
  getConsumptionList,
  dictType,
  getTransList,
  getCarList,
  upload,
  addTemporary,
} = require('../../utils/api');
const { formatDate, validateFields } = require('../../utils/tool');
let managerUserList = []; // 消纳场列表
let garbageTypeList = []; // 垃圾类型列表
let projectTypeList = []; // 工程类型列表
let transList = []; // 外运输单位列表
let selfCarList = []; // 本单位车辆列表
let carIdList = []; // 车辆列表
let transId = '';

const rules = {
  projectName: '请输入项目名称',
  company: '请输入施工单位',
  managerUserId: '请选择消纳场',
  garbageType: '请选择垃圾类型',
  projectType: '请选择工程类型',
  startTime: '请选择工程开始时间',
  endTime: '请选择工程结束时间',
  imgs: '请上传路线证明',
  selfCarList: '请选择本单位车辆',
  transList: '请选择外运输单位',
  carIdList: '请选择车辆',
  cnsx: '请阅读保洁责任承诺事项',
};

const MAXDATE = new Date('2050-12-31 11:59:59').getTime();

Page({
  data: {
    loading: false,
    checkboxResult: [],
    checkboxColumns: [],
    checkboxLabel: '',
    checkboxValue: '',
    columns: [],
    columnsKey: '',
    showPopup: false,
    currentPicker: '',
    showTimePopup: false,
    showCheckboxPopup: false,
    currentTimePicker: '',
    minDate: new Date().getTime(),
    maxDate: MAXDATE,
    currentDate: new Date().getTime(),
    managerUserName: '', // 消纳场名称
    garbageTypeName: '', // 垃圾类型名称
    projectTypeName: '', // 工程类型名称
    selfCarNames: '', // 本单位车辆名称
    transIdNames: '', // 外运输单位名称
    carIdNames: '', // 车辆名称
    form: {
      projectName: '', // 项目名称
      company: '', // 施工单位
      managerUserId: '', // 消纳场
      garbageType: '', // 垃圾类型
      projectType: '', // 工程类型
      startTime: '', // 运输起始时间
      endTime: '', // 运输结束时间
      pathName: '', // 运输路线
      imgs: [], // 路线证明
      selfCarList: [], // 本单位车辆
      transList: [], // 外运输单位
      carIdList: [], // 车辆
      cnsx: false,
    },
  },

  onLoad() {
    getAppUser().then((res) => {
      transId = res?.data?.id;
    });
    getConsumptionList().then((res) => {
      managerUserList = res.data;
    });
    dictType('bus_project_location').then((res) => {
      garbageTypeList = res.data;
    });
    dictType('bus_engin_type').then((res) => {
      projectTypeList = res.data;
    });
    getTransList().then((res) => {
      transList = res.data;
    });
  },

  handlePickerTap(e) {
    const { type } = e.currentTarget?.dataset || {};
    let columns = [];
    let columnsKey = '';
    switch (type) {
      case 'managerUserId':
        columns = managerUserList;
        columnsKey = 'names';
        break;
      case 'garbageType':
        columns = garbageTypeList;
        columnsKey = 'dictLabel';
        break;
      case 'projectType':
        columns = projectTypeList;
        columnsKey = 'dictLabel';
        break;
    }

    this.setData({
      currentPicker: type,
      columns,
      columnsKey,
      showPopup: true,
    });
  },

  handlePickerCheckboxTap(e) {
    const { type } = e.currentTarget?.dataset || {};
    let checkboxColumns = [];
    let checkboxLabel = '';
    let checkboxValue = '';
    switch (type) {
      case 'selfCarList':
        checkboxColumns = selfCarList;
        checkboxLabel = 'licensePlate';
        checkboxValue = 'id';
        break;

      case 'transList':
        checkboxColumns = transList;
        checkboxLabel = 'company';
        checkboxValue = 'id';
        break;

      case 'carIdList':
        checkboxColumns = carIdList;
        checkboxLabel = 'licensePlate';
        checkboxValue = 'id';
        break;
    }

    this.setData({
      currentPicker: type,
      checkboxColumns,
      checkboxLabel,
      checkboxValue,
      showCheckboxPopup: true,
    });

    setTimeout(() => {
      this.setData({
        checkboxResult: this.data.form[type],
      });
    }, 100);
  },

  onCheckboxChange(e) {
    this.setData({
      checkboxResult: e.detail,
    });
  },

  onCheckboxConfirm() {
    const { currentPicker, checkboxResult } = this.data;
    switch (currentPicker) {
      case 'selfCarList':
        this.setData({
          ['form.selfCarList']: checkboxResult,
          selfCarNames: checkboxResult.map((item) => {
            return selfCarList.find((trans) => trans.id == item).licensePlate;
          }),
          showCheckboxPopup: false,
        });
        break;

      case 'transList':
        this.setData({
          ['form.transList']: checkboxResult,
          transNames: checkboxResult.map((item) => {
            return transList.find((trans) => trans.id == item).company;
          }),
          showCheckboxPopup: false,
        });
        this.getCarListByTrans({ companyIds: checkboxResult });
        break;

      case 'carIdList':
        this.setData({
          ['form.carIdList']: checkboxResult,
          carIdNames: checkboxResult.map((item) => {
            return carIdList.find((trans) => trans.id == item).licensePlate;
          }),
          showCheckboxPopup: false,
        });
        break;
    }
  },

  getCarListByTrans({ startTime, companyIds }) {
    if (startTime) {
      getCarList({ startTime, companyIds: transId }).then((res) => {
        selfCarList = res.data;
      });
      getCarList({ startTime }).then((res) => {
        carIdList = res.data;
      });
    } else {
      const stime = this.data.form.startTime;
      getCarList({ startTime: stime, companyIds: companyIds?.join?.(',') }).then((res) => {
        carIdList = res.data;
      });
    }
  },

  onConfirm(e) {
    const { value } = e.detail;
    const currentPicker = this.data.currentPicker;

    switch (currentPicker) {
      case 'managerUserId':
        this.setData({
          ['form.managerUserId']: value.id,
          managerUserName: value.names,
          showPopup: false,
        });
        break;
      case 'garbageType':
        this.setData({
          ['form.garbageType']: value.dictValue,
          garbageTypeName: value.dictLabel,
          showPopup: false,
        });
        break;
      case 'projectType':
        this.setData({
          ['form.projectType']: value.dictValue,
          projectTypeName: value.dictLabel,
          showPopup: false,
        });
        break;
    }
  },

  onCancel() {
    this.setData({
      showPopup: false,
      showTimePopup: false,
      showCheckboxPopup: false,
    });
  },

  onTimeConfirm(e) {
    const time = e.detail;
    const { currentTimePicker } = this.data;
    const formatTime = formatDate(time);
    let dataKey = '';
    switch (currentTimePicker) {
      case 'startTime':
        dataKey = 'form.startTime';
        this.getCarListByTrans({ startTime: formatTime });
        break;
      case 'endTime':
        dataKey = 'form.endTime';
        break;
    }
    this.setData({
      [dataKey]: formatTime,
      showTimePopup: false,
    });
  },

  handlePickerTimeTap(e) {
    const type = e.currentTarget.dataset.type;
    if (type === 'startTime') {
      if (this.data.form.endTime) {
        this.setData({
          minDate: new Date().getTime(),
          maxDate: new Date(this.data.form.endTime).getTime(),
        });
      }
    }
    if (type === 'endTime') {
      if (this.data.form.startTime) {
        this.setData({
          minDate: new Date(this.data.form.startTime).getTime(),
          maxDate: MAXDATE,
        });
      }
    }
    this.setData({
      showTimePopup: true,
      currentTimePicker: type,
    });
  },

  handleFieldInput(e) {
    const { type } = e.currentTarget.dataset;
    this.setData({
      [`form.${type}`]: e.detail,
    });
  },

  handleViewAddress() {
    wx.authorize({
      scope: 'scope.userLocation',
      success: async () => {
        const { addrGis } = this.data.form || {};
        if (addrGis) {
          let longitude = '';
          let latitude = '';
          const g = addrGis.split(',');
          longitude = g?.[0];
          latitude = g?.[1];
          wx.openLocation({
            longitude: Number(longitude || ''),
            latitude: Number(latitude || ''),
            complete: (res) => {
              console.log(res);
            },
          });
        }
      },
    });
  },

  handleAfterRead(e) {
    const { file } = e.detail;
    const { imgs } = this.data.form;
    upload(file.url).then((res) => {
      this.setData({
        ['form.imgs']: [...imgs, { url: res.url }],
      });
    });
  },

  handleDelete(e) {
    const { index } = e.detail;
    const { imgs } = this.data.form;
    this.setData({
      ['form.imgs']: imgs.filter((_, i) => i !== index),
    });
  },

  handleCnsxCheck() {
    this.setData({
      ['form.cnsx']: !this.data.form.cnsx,
    });
  },

  handleSubmit() {
    const { form } = this.data;
    if (!validateFields(form, rules)) {
      return;
    }
    const newForm = JSON.parse(JSON.stringify(form));
    newForm.appUserId = transId;
    newForm.transList = newForm?.transList?.toString?.();
    newForm.carIdList = newForm?.carIdList?.toString?.();
    newForm.selfCarList = newForm?.selfCarList?.toString?.();
    newForm.imgs = newForm?.imgs?.map?.((item) => item.url)?.join?.(',');
    newForm.cnsx = Number(newForm.cnsx);
    newForm.type = 1;
    this.setData({ loading: true });
    addTemporary(newForm)
      .then((res) => {
        this.setData({ loading: false });
        wx.showToast({
          title: '提交成功',
          icon: 'success',
          duration: 2000,
        });
        setTimeout(() => {
          wx.navigateBack();
        }, 2000);
      })
      .catch(() => {
        this.setData({ loading: false });
        wx.showToast({ title: '提交失败', icon: 'error' });
      });
  },
});
